package cc.rengu.igas.momp.common.dao.impl;

import cc.rengu.igas.momp.common.constant.CommonConstant;
import cc.rengu.igas.momp.common.constant.DatabaseLabelConstant;
import cc.rengu.igas.momp.common.dao.MompSequenceMapper;
import cc.rengu.jradp.mods.dbs.Database;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.utility.util.DbsUtil;
import cc.rengu.oltp.utility.util.XmlConfigUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.cache.UnifiedCache;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;

/**
 * Sequence接口实现
 *
 * @author Jinan Liu
 * @date 2020/5/21 14:40
 */
public class MompSequenceMapperImpl implements MompSequenceMapper {

    private RgLogger rglog = RgLog.getLogger(this.getClass().getName());
    String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppParamConstant.DATABASE_CONF_NODE, AppConfigConstant.MOMP_POOL_NAME);

    /**
     * 获取营销活动编号sequence接口实现
     *
     * @return java.lang.String
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/21 14:41
     */
    @Override
    public String getMompNextMaNoSeq() throws Exception {

        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MOMP_POOL_NAME);
        }
        rglog.error("DBPoolName=[{}]", dbPoolName);

        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "getMompNextMaNoSeq");

        int iReturnCode = dbsUtil.dbsExecuteSql(sqlStr, null, null);
        if (Database.DBS_SUCCESS != iReturnCode) {
            rglog.error("获取商户序号SEQUENCE失败,iReturnCode:<{}>", iReturnCode);
            return null;
        }

        /* 不足长度前补0 */
        String maNoSequence = xmlTreeUtil.getXmlTreeStringValue(DatabaseLabelConstant.MC_NO_SEQ);
        if (maNoSequence.length() < CommonConstant.ELEVEN) {
            String format = "%0" + (CommonConstant.ELEVEN - maNoSequence.length()) + "d";
            return String.format(format, 0) + maNoSequence;
        } else {
            return maNoSequence;
        }
    }
}
